package com.sunzn.media.library.drag;

import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;

public class OnMediaItemTouchListener implements RecyclerView.OnItemTouchListener {

    private final GestureDetectorCompat mDetectorCompat;

    public OnMediaItemTouchListener(RecyclerView recyclerView, OnItemListener mListener) {
        mDetectorCompat = new GestureDetectorCompat(recyclerView.getContext(), new RecyclerViewGestureDetector(recyclerView, mListener));
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull RecyclerView recyclerView, @NonNull MotionEvent motionEvent) {
        mDetectorCompat.onTouchEvent(motionEvent);
        return false;
    }

    @Override
    public void onTouchEvent(@NonNull RecyclerView recyclerView, @NonNull MotionEvent motionEvent) {
        mDetectorCompat.onTouchEvent(motionEvent);
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean b) {

    }

    static class RecyclerViewGestureDetector extends GestureDetector.SimpleOnGestureListener {

        private final RecyclerView mRecyclerView;
        private final OnItemListener mListener;

        RecyclerViewGestureDetector(RecyclerView mRecyclerView, OnItemListener listener) {
            this.mRecyclerView = mRecyclerView;
            this.mListener = listener;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            View childView = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
            if (childView != null) {
                int pos = mRecyclerView.getChildAdapterPosition(childView);
                if (pos > -1 && mListener != null) {
                    mListener.onItemClick(pos);
                }
            }
            return super.onSingleTapUp(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
            View childView = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
            if (childView != null) {
                RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(childView);
                if (holder != null && mListener != null) {
                    mListener.onItemLongClick(holder);
                }
            }
        }
    }

    public interface OnItemListener {

        void onItemClick(int pos);

        void onItemLongClick(RecyclerView.ViewHolder holder);

    }

}
